package it.webbased.site.client;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/*
 * Map API Keys: 
 * http://www.webbased.it/
 * ABQIAAAAcU7VerGjBwvidhn5mpls_hQZUMsNEDFBjxWP0qpmNQYx4_cIQRSVJS7NSyZa_3mdbyDqkCk9XEdYqA
 *
 * http://localhost/
 * ABQIAAAAcU7VerGjBwvidhn5mpls_hT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTomr0cQV9_yqWC0FaWfDkZKmzQbg  
 */
public class WebBased implements EntryPoint {

	private class Page extends Composite {

		private String id;
		private String title;
		private int index;

		private HTML html;

		public Page(Element e) {
			html = HTML.wrap(e);
			initWidget(html);
			setStylePrimaryName("wb-Page");
		}

		public Page(Widget w) {
			initWidget(w);
			setStylePrimaryName("wb-Page");
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getId() {
			return id;
		}

		public int getIndex() {
			return index;
		}

		public void setTitle(String title) {
			this.title = title;
		}

		public String getTitle() {
			return title;
		}
	}

	private Map<String, Page> pages = new HashMap<String, Page>();

	private String firstPageToken;

	private DecoratedTabPanel tabPanel;
	private VerticalPanel headerPanel;
	private ContactPanel contactPanel;
	private HTML footerPanel;
	private Anchor logo;
	private boolean historyBrowse = false;

	public void onModuleLoad() {

		contactPanel = new ContactPanel();

		loadStaticStuff();

		createTabPanel();
		createHeaderPanel();
		createFooterPanel();
		removeStaticStuff();

		HorizontalPanel hp = new HorizontalPanel();
		hp.setWidth("100%");
		hp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		DockPanel mainPanel = new DockPanel();
		mainPanel.setStylePrimaryName("wb-Main");
		mainPanel.add(headerPanel, DockPanel.NORTH);
		mainPanel.add(tabPanel, DockPanel.CENTER);
		mainPanel.add(footerPanel, DockPanel.SOUTH);
		hp.add(mainPanel);
		RootPanel.get().add(hp);
		final Element loadingDiv = DOM.getElementById("loadingDiv");
		initHistory();

		Timer loading = new Timer() {

			@Override
			public void run() {
				Document.get().getBody().removeChild(loadingDiv);

			}
		};
		loading.schedule(200);
	}

	private void removeStaticStuff() {
		Element e = DOM.getElementById("stuff");
		e.getParentElement().removeChild(e);
	}

	private void createFooterPanel() {
		footerPanel = HTML.wrap(DOM.getElementById("footer"));
		footerPanel.setStylePrimaryName("wb-Footer");
	}

	private void initHistory() {

		History.addValueChangeHandler(new ValueChangeHandler<String>() {
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				processHistoryChange(event.getValue());
			}
		});

		History.fireCurrentHistoryState();
	}

	private void createHeaderPanel() {

		logo = new Anchor("logo WebBased.it", "#");
		logo.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				History.newItem(firstPageToken);
			}
		});
		logo.setStylePrimaryName("wb-Logo");
		Element logoElem = DOM.getElementById("logo");
		HTML img = HTML.wrap(logoElem);
		logo.setHTML(img.getHTML());

		/*
		 * Anchor contattaciLink = new Anchor("Contattaci",
		 * "mailto:info@webbased.it");
		 */

		headerPanel = new VerticalPanel();
		headerPanel.setStylePrimaryName("wb-Header");
		headerPanel.setWidth("100%");
		headerPanel.add(logo);
		/*
		 * headerPanel.add(contattaciLink);
		 * headerPanel.setCellHorizontalAlignment(contattaciLink,
		 * HasHorizontalAlignment.ALIGN_RIGHT);
		 */
	}

	private void processHistoryChange(String token) {
		Page p = pages.get(token);
		historyBrowse = true;
		if (p != null && !p.equals(firstPageToken)) {
			tabPanel.selectTab(p.getIndex());
		} else {
			tabPanel.selectTab(0);
		}
	}

	private void loadStaticStuff() {

		Element pagesElem = DOM.getElementById("pages");

		int index = 0;
		for (Element pageElem = pagesElem.getFirstChildElement(); pageElem != null; pageElem = pageElem
				.getNextSiblingElement()) {

			String id = pageElem.getId();
			pageElem.setId("_" + id);
			String title = pageElem.getTitle();

			Page page = new Page(pageElem);
			page.setIndex(index++);
			page.setId(id);
			page.setTitle(title);

			pages.put(id, page);
		}
		Page page = new Page(contactPanel);
		page.setIndex(index++);
		page.setId("contatti");
		page.setTitle("Contatti");
		pages.put("contatti", page);
	}

	private void createTabPanel() {

		tabPanel = new DecoratedTabPanel();
		tabPanel.setStylePrimaryName("wb-Nav");
		tabPanel.setAnimationEnabled(true);
		tabPanel.setWidth("100%");

		Page[] sortPages = pages.values().toArray(new Page[0]);
		Arrays.sort(sortPages, new Comparator<Page>() {
			@Override
			public int compare(Page p1, Page p2) {
				return ((Integer) p1.getIndex()).compareTo(p2.getIndex());
			}
		});

		contactPanel.setRedirect(firstPageToken = sortPages[0].getId());

		for (Page p : sortPages) {
			tabPanel.add(p, p.getTitle());
		}

		tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
			@Override
			public void onSelection(SelectionEvent<Integer> event) {
				int index = event.getSelectedItem();
				logo.setFocus(true);
				logo.setFocus(false);
				Page p = (Page) tabPanel.getWidget(index);
				trackSelection("/#" + p.getId());
				if (historyBrowse) {
					historyBrowse = false;
				} else {
					History.newItem(p.getId(), false);
				}
			}
		});
	}

	public native void trackSelection(String page) /*-{
		try {
		$wnd.pageTracker._trackPageview(page);
		} catch(err) {}
	}-*/;

}
